import * as IConstant from '../../../core/utils/IConstant';
import HttpClient from '../../../core/utils/HttpClient';
import '../../../core/utils/DateUtil';

export function setSelectedTabIndexAction(index)
{
    return {
        type: IConstant.Actions.NEWS.LIST.SET_SELECTED_TAB_INDEX,
        index: index
    };
}

export function asyncGetListAction(key, pageIndex)
{
    return function(dispatch, getState)
    {
        dispatch(_getListRequestAction(key, pageIndex));
        return _fetchList(key, pageIndex).then((resp)=>{
            dispatch(_getListSuccessAction(key, pageIndex, resp));
        }).catch((error)=>{
            dispatch(_getListFailureAction(key, error));
        });
    };
}

export function goBackAction()
{
    return {
        type: IConstant.Actions.NEWS.LIST.GO_BACK,
    };
}

export function asyncDeleteListAction(key)
{
    return function(dispatch, getState)
    {
        dispatch(deleteListAction(key));
        return new Promise((resolve)=>{
            resolve();
        });
    };
}

export function deleteListAction(key)
{
    return {
        type: IConstant.Actions.NEWS.LIST.DELETE,
        key,
    };
}

export function setScrollerPositionAction(key, offset)
{
    return {
        type: IConstant.Actions.NEWS.LIST.SET_LISTVIEW_OFFSET,
        key,
        listViewOffset: offset
    };
}

export function increaseClickCountAction(key, code)
{
    return {
        type: IConstant.Actions.NEWS.LIST.INCREASE_CLICK_COUNT,
        key,
        code,
    };
}

function _fetchList(key, pageIndex)
{
    let kvDict = {
        Identifier: key,
        pageIndex: pageIndex,
        pageSize: IConstant.PAGE_SIZE
    };

    return HttpClient.getFromPortal(IConstant.PortalApis.NEWS.LIST, kvDict)
        .then((resp) => resp.json());
}

function _getListRequestAction(key, pageIndex)
{
    return {
        type: IConstant.Actions.NEWS.LIST.GET_LIST_REQUEST,
        key,
        pageIndex,
    };
}

function _getListSuccessAction(key, pageIndex, result)
{
    return {
        type: IConstant.Actions.NEWS.LIST.GET_LIST_SUCCESS,
        key,
        pageIndex,
        result
    };
}

function _getListFailureAction(key, error)
{
    return {
        type: IConstant.Actions.NEWS.LIST.GET_LIST_FAILURE,
        key,
        message: error
    };
}